package com.workflow.engine.eb.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Field;

public class LuaProcess {

	public static Logger logger = LoggerFactory.getLogger(LuaProcess.class);

	private int processId;

	public LuaProcess() {
		String jdkver = System.getProperty("sun.arch.data.model");
		if (jdkver.compareTo("64") == 0) {
			System.loadLibrary("XpLib.x64");
		} else {
			System.loadLibrary("XpLib.x86");
		}
		logger.info("LuaProcess init ok!");
	}

	public LuaProcess(String DllPath) {
		logger.info("LuaProcess init start!");
		try {
			AddDir(DllPath);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		String jdkver = System.getProperty("sun.arch.data.model");
		logger.info("jdkver " + jdkver);
		try {
			if (jdkver.compareTo("64") == 0) {
				System.loadLibrary("XpLib.x64");
			} else {
				System.loadLibrary("XpLib.x86");
			}
		} catch (Exception e) {
			logger.error("初始化类库失败 : " + e.getMessage(), e);
		}
		logger.info("LuaProcess init ok!");
	}

	private static void AddDir(String s) throws IOException {
		try {
			logger.info("AddDir init start!");
			Field field = ClassLoader.class.getDeclaredField("usr_paths");
			field.setAccessible(true);
			String[] paths = (String[]) field.get(null);
			for (int i = 0; i < paths.length; i++) {
				if (s.equals(paths[i])) {
					logger.info("AddDir " + paths[i]);
					return;
				}
			}
			String[] tmp = new String[paths.length + 1];
			System.arraycopy(paths, 0, tmp, 0, paths.length);
			tmp[paths.length] = s;
			field.set(null, tmp);
		} catch (IllegalAccessException e) {
			throw new IOException("Failed to get permissions to set library path");
		} catch (NoSuchFieldException e) {
			throw new IOException("Failed to get field handle to set library path");
		}
		logger.info("AddDir init ok!");
	}

	public int getProcessId() {
		return processId;
	}

	public native int Create(String ScriptId);

	public native boolean Send(String Param);

	public native String Receive();

	public native boolean IsExist();

	public native boolean Close();
}
